import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { UserManageService } from './user-manage.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { from } from 'rxjs';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { emailValidator } from 'src/app/h-common/validators/email-valid.directive';
import { phoneValidator } from 'src/app/h-common/validators/phone-valid.directive';
import { HCommonService } from 'src/app/h-common/h-common.service';
import { Router } from '@angular/router';
@Component({
    selector: 'app-user-manage',
    templateUrl: './user-manage.component.html',
    styleUrls: ['./user-manage.component.scss']
})

export class UserManageComponent implements OnInit {
    userForm: FormGroup;
    editId: number;
    listOfAllData = [];
    isCheckAll = false;
    isIndeterminate = false;
    mapOfCheckedId: { [key: string]: boolean } = {};
    roleList = [];
    isVisible: boolean = false;
    isOkLoading: boolean = false;
    statusValue: string | boolean = '';//状态 激活 锁定
    dateRange = [];//日期选择
    searchValue: string = '';//模糊搜索
    departValue: string = '';//部门名称
    nodes = [];//左侧树状结构
    pageIndex: number = 1;//提交的页码
    pagesize: number = 10;//table每页条数
    totalSize: any = '';//总共条数
    bornRoles = {};
    listOfSelectedValue=[];
    modalDomBox: any

    private deleteMember = [];//删除的人员
    private deptId: any = '';//部门id

    constructor(
        private userManageService: UserManageService,
        private datePipe: DatePipe,
        private message: NzMessageService,
        private modalService: NzModalService,
        private fb: FormBuilder,
        private commonService: HCommonService,
        private router: Router
    ) { }

    ngOnInit() {
        this.modalDomBox = document.querySelector("#modal_box");

        /* 获取权限 */
        this.bornRoles = this.commonService.getRoles("user");

        this.userForm = this.fb.group({
            username: [null, [Validators.required]],
            // phone: [null, [Validators.required, phoneValidator]],
            phone: [null, [phoneValidator]],
            userPassword: [null, []],
            // nickName: [null, [Validators.required]],
            nickName: [null],
            // email: [null, [Validators.required, emailValidator]],
            email: [null, [emailValidator]],
            sex: ["男"],
            enabled: [true],
            deptId: [null, [Validators.required]],
            // rolesId: ["", [Validators.required]]
            rolesId: [[], Validators.required],
        })

        this.getNodes()
        this.getMember()
        this.getRoleList()
    }
    // 左上搜索部门
    fillDepart(name) {
        this.departValue = name
        this.getNodes();
        if (!name) {
            this.deptId = "";
            this.getMember();
        }
    }
    // 点击树节点
    clickDepart(data) {
        this.deptId = data.nodes[0].origin.key;
        this.getMember()
    }
    // 日期选择
    onDateChange(result: Date): void {
        let startTime = this.formatDate(result[0])
        let endTime = this.formatDate(result[1])
        this.dateRange = [startTime + " 00:00:00", endTime + " 23:59:59"]
        this.pageIndex = 1;
        this.getMember();
    }
    // 时间格式化
    formatDate(date) {
        return this.datePipe.transform(date, 'yyyy-MM-dd');
    }
    // 选择状态
    selectStatus(status) {
        this.statusValue = status;
        this.pageIndex = 1;
        this.getMember();
    }
    // 点击分页事件
    clickPage(pageIndex) {
        this.pageIndex = pageIndex
        this.getMember()
    }

    showModal(type): void {
        this.isVisible = true;
        if (type == 2) {
            let _data = this.listOfAllData.filter(item => {
                return item.id == this.deleteMember[0]
            })[0]
            this.editId = _data.id;
            let resultRoleIds = _data.roles.map(item=>{
                return item.id
            })
            this.userForm.patchValue({
                username: _data.username,
                phone: _data.phone,
                nickName: _data.nickName,
                email: _data.email,
                sex: _data.sex,
                enabled: _data.enabled,
                deptId: _data.dept.id,
                // rolesId: _data.roles[0].id
                rolesId: resultRoleIds
            })
        } else {
            this.editId = -1;
            this.userForm.reset({
                sex: "男",
                enabled: true,
                // rolesId: ""
                rolesId: [],
            })
        }
    }
    // 取消按钮
    handleCancel(): void {
        this.isVisible = false;
    }
    submitFn() {
        var _dataJson = {}
        for (const i in this.userForm.controls) {
            this.userForm.controls[i].markAsDirty();
            this.userForm.controls[i].updateValueAndValidity();
            _dataJson[i] = this.userForm.controls[i].value
        }
        //  let _formValue = this.userForm.value;
        if (this.userForm.status === "VALID") {
            if (this.editId == -1) {
                this.add(_dataJson);
            } else {
                this.edit(_dataJson)
            }
        };
    }
    initStatus() {
        this.deleteMember = []
        this.mapOfCheckedId = {};
        this.isCheckAll = this.isIndeterminate = false;
        this.getMember();
    }
    add(data) {
        this.userManageService.addMember(data).subscribe(res => {
            this.isVisible = false;
            this.initStatus();
        })
    }
    edit(data) {
        let _dataJson = {
            ...data,
            id: this.editId
        }
        this.userManageService.putMember(_dataJson).subscribe(res => {
            this.isVisible = false;
            this.initStatus();
        })
    }

    // 获取右侧人员表格
    getMember() {
        let data = {
            page: this.pageIndex,
            size: this.pagesize,
            blurry: this.searchValue,
            createTime: this.dateRange,
            deptId: this.deptId,
            enabled: this.statusValue
        }
        this.userManageService.getDepartMember(data).subscribe(res => {
            this.totalSize = res.totalElements
           
            let newList = res.content;
            for (let i = 0; i < newList.length; i++) {
                newList[i].deptName = newList[i].dept.name
            }
            newList.forEach(item=>{
                let roleStr=[];
                item.roles.forEach(itemRole=>{
                    roleStr.push(itemRole.name)
                 });
                 item.roleStr=roleStr.join(",");
             });
          
            this.listOfAllData = newList
        })

    }
    switchChange(data) {
        this.editId = data.id;
        let _dataJson = {
            username: data.username,
            phone: data.phone,
            nickName: data.nickName,
            email: data.email,
            sex: data.sex,
            enabled: data.enabled,
            deptId: data.dept.id,
            rolesId: data.roles[0].id
        }
        this.edit(_dataJson)
    }
    checkAll(value: boolean): void {
        this.listOfAllData.forEach(item => {
            this.mapOfCheckedId[item.id] = value
        })
        this.isIndeterminate = false;
        this.filterDelData();
    }
    refreshStatus(): void {
        this.isCheckAll = this.listOfAllData.every(item => {
            return this.mapOfCheckedId[item.id]
        })
        this.isIndeterminate = this.listOfAllData.some(item => {
            return this.mapOfCheckedId[item.id] && !this.isCheckAll
        })
        this.filterDelData();
    }
    // 过滤要删除的数据
    filterDelData() {
        this.deleteMember = [];
        for (const key in this.mapOfCheckedId) {
            const item = this.mapOfCheckedId[key];
            if (item) {
                this.deleteMember.push(key)
            }
        }
    }
    deleteMemberFn() {
        this.modalService.confirm({
            nzTitle: '确定要删除这些人员吗？',
            nzContent: '',
            nzOkText: '确认',
            nzCancelText: '取消',
            nzOnOk: () => {
                this.userManageService.deleteMember(this.deleteMember).subscribe(res => {
                    this.initStatus();
                })
            }
        });
    }

    // 获取所有角色
    getRoleList() {
        this.userManageService.getRoleList().subscribe(res => {
            this.roleList = res
        })
    }
    // 获取左侧树状结构
    getNodes() {
        this.userManageService.getDepartNodes(this.departValue).subscribe((res) => {
            this.nodes = this.initHtree(res.content);
        });
    }
    // 初始化部门树
    initHtree(data) {
        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                data[i].title = data[i].name;
                data[i].key = data[i].id;
                if (data[i].children) {
                    this.initHtree(data[i].children)
                }
                else {
                    data[i].expanded = true;
                    data[i].isLeaf = true;
                }
            }
        }
        return data
    }

    // 导出数据
    async downloadList() {
        let data = {
            blurry: this.searchValue,
            createTime: this.dateRange,
            deptId: this.deptId,
            enabled: this.statusValue
        }
        let list: any = await this.userManageService.downMember(data)
    }

}
